<template>
  <div class="upload-container">
    <el-button :style="{background:color,borderColor:color}" icon="el-icon-upload" size="mini" type="primary" @click=" dialogVisible=true" round>选择图片
    </el-button>
    <el-dialog :visible.sync="dialogVisible">
      <el-upload
        action="''"
        multiple
        list-type="picture-card"
        :http-request="upload"
        :on-success="handleSuccess"
        :before-upload="beforeAvatarUpload">
        <el-button size="small" type="primary" round>本地选择图片</el-button>
      </el-upload>
      <div class="tar">
        <el-button @click="dialogVisible = false" round size="small">取 消</el-button>
        <el-button type="primary" @click="handleSubmit" round size="small">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>

import { createId } from '@/utils/index' // 一个生产唯一的id的方法
import OSS from 'ali-oss'
import { selectOSSInfo } from '@/api/set/oss'
export default {
  name: 'EditorSlideUpload',
  props: {
    color: {
      type: String,
      default: '#1890ff'
    }
  },
  data() {
    return {
      dialogVisible: false,
      listObj: [],
      fileList: [],
      uploadParams:{
        uploadPath: '',
        uploadSize: ''
      },
      dialogImageUrl: '',
      imageUrl: '',
      filePath: '',
      batchList: [],
      tempArr: [],
      ossData:{
        region:'',// 服务器集群地区
        accessKeyId:'',// OSS帐号
        accessKeySecret:'',// OSS 密码
        bucket:'',// 阿里云上存储的 Bucket
      }
    }
  },
  created() {
    selectOSSInfo().then(res=>{
      if(res.code==1){
        // res.data=JSON.parse(this.$base64.decode(res.data));
        this.ossData.region=res.data.oss_region;
        this.ossData.accessKeyId=res.data.oss_accessKeyId;
        this.ossData.accessKeySecret=res.data.oss_accessKeySecret;
        this.ossData.bucket=res.data.oss_backetName;
      }
  
    })
  },
  methods: {
    handleSubmit() {
      const arr = Object.keys(this.listObj).map(v => this.listObj[v])
      this.$emit('successCBK', arr)
      this.listObj = []
      this.fileList = []
      this.dialogVisible = false
    },
    // 图片上传前验证
    beforeAvatarUpload (file) {
        // file.size / 1024 图片的大小
        const format = /^image\/(jpeg|png|gif|bmp|jpg)$/.test(file.type);
        const isLt1M = file.size / 1024 / 1024 < 1;
        this.uploadParams.uploadSize = file.size
        if (!format) {
        this.$message.error('上传图片只能是 JPG，PNG，GIF格式!');
        }
        if (!isLt1M) {
        this.$message.error('上传图片大小不能超过 1MB!');
        }
        return format && isLt1M;
    },
    // 上传图片到OSS 同时派发一个事件给父组件监听
    upload (item) {
        let type
        let client = new OSS({
          region: this.ossData.region,
          accessKeyId: this.ossData.accessKeyId,
          accessKeySecret: this.ossData.accessKeySecret,
          bucket: this.ossData.bucket
        })
        switch (item.file.type) {
          case 'image/jpeg': {
            type = 'jpeg'
          }break;
          case 'image/jpg': {
            type = 'jpg'
          }break;
          case 'image/gif': {
            type = 'gif'
          }break;
          case 'image/png': {
            type = 'png'
          }break;
        }
        this.batchList.push({
          name: item.file.name,
          url: ''
        })
        this.tempArr.push({
          name: item.file.name,
          url: ''
        })
        let key = 'BCenter/time=' + new Date().getTime() + '&id=' + this.guidGenerator() + '.' + type// 存储路径，并且给图片改成唯一名字
        return client.put(key, item.file).then( res => {   // OSS上传
            const url = res.url
            this.uploadParams.uploadPath = client.signatureUrl(key,{ expires: 999999999999999 })   // 可访问的链接
            this.batchList.push({
              name: item.file.name,
              url: this.uploadParams.uploadPath
            })
            this.batchList = this.batchList.slice(this.batchList.length / 2, this.batchList.length)
        })
    },
    guidGenerator() {
        var S4 = function() {
          return ((1 + Math.random())*0X10000|0).toString(16).substring(1);
        };
        return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());
    },
    handleSuccess(res, file){
      this.filePath = URL.createObjectURL(file.raw)
      this.fileList = []
      for(var i =0; i < this.batchList.length;i++) {
        for(var j = 0;j < this.tempArr.length;j++) {
          if(this.tempArr[j].name == this.batchList[i].name) {
            this.tempArr[j].url = this.batchList[i].url
          }
        }
      } 
      for(var k = 0;k < this.tempArr.length;k++) {
        this.listObj[k] = this.tempArr[k].url
      }
    },
    handlePictureCardPreview(file) {
        this.dialogImageUrl = file.url;
        this.dialogVisible = true;
    },

  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.editor-slide-upload {
  margin-bottom: 20px;
  /deep/ .el-upload--picture-card {
    width: 100%;
  }
}
</style>
